package net.borderwars.util;

import java.util.Collection;
import java.util.Map;

/**
 * @author ehubbard
 *         Date: Aug 5, 2005
 *         Time: 11:32:06 AM
 */
abstract public class MapOfCollection<Key, Value> {
    protected abstract Collection<Value> getCollection ();

    protected abstract Map<Key, Collection<Value>> getMap ();

    protected Map<Key, Collection<Value>> data = null;

    public MapOfCollection () {
        data = getMap ();
    }

    public void put (Key k, Value v) {
        Collection<Value> bucket = getBucket (k);
        bucket.add (v);
    }

    public Collection<Value> getItems (Key k) {
        return (getBucket (k));
    }

    private Collection<Value> getBucket (Key k) {
        if (data.containsKey (k)) {
            return (data.get (k));
        }
        else {
            Collection<Value> c = getCollection ();
            data.put (k, c);
            return (c);
        }
    }

    public String toString () {
        StringBuffer sb = new StringBuffer (300);
        for (Key k : data.keySet ()) {
            sb.append ("Key: " + k + "\n");
            for (Object v : getBucket (k)) {
                sb.append ("\t" + v + "\n");
            }
        }
        return (sb.toString ());
    }

}
